let g:matlabOutput = ''

function! matlab#error(message) abort
	echohl matlabError
	echoerr printf(a:message)
	echohl None
endfunction

function! matlab#print(message) abort
	echohl matlabString
	echomsg printf(a:message)
	echohl None
endfunction


function! matlab#execute(code) abort
	pyx <<EOF
import vim
import win32
from win32com.client import DispatchEx
if 'matlabInstance' not in dir() or matlabInstance is None:
	try:
		matlabInstance = DispatchEx('MATLAB.Desktop.Application')
	except Exception as e:
		print(e)
output = matlabInstance.Execute(vim.eval('a:code'))
vim.vars['matlabOutput'] = output
EOF
	call matlab#print(g:matlabOutput)
	return g:matlabOutput
endfunction

function! matlab#run(...) abort
	if a:0 < 1
		let file = expand('%:p')
	else
		let file = a:1
	endif 
	if filereadable(file)
		let directory = fnamemodify(file, ':p:h')
		let name = fnamemodify(file, ':t:r')
		let package = fnamemodify(directory, ':t')
		while package[0] == '+'
			let name = package[1:] . '.' . name 
			let directory = fnamemodify(directory, ':h')
			let package = fnamemodify(directory, ':t')
		endwhile
		let cmd = 'cd ' . directory
		let output = matlab#execute(cmd)
		if output == ''
			return matlab#execute(name)
		else
			call matlab#error(output)
		endif
	else
		call matlab#error('file ' . a:file . ' not found')
	endif
endfunction
